use base64::{Engine as _, engine::general_purpose};
use std::fs;
use std::process::Command;

//从assets/style.CSS读取CSS文件的内容
pub fn read_style_css() -> String {
    fs::read_to_string("static/style.css").unwrap_or_else(|_| String::from(""))
}

//读取给定路径下的资产文件，并返回一个base64编码的字符串
pub fn read_asset_base64(path: &str) -> String {
    match fs::read(path) {
        Ok(bytes) => general_purpose::STANDARD.encode(bytes),
        Err(_) => String::from(""),
    }
}

//从资源中读取字体文件和favicon并返回（font_regular、font_media、font_light、favicon）
pub fn read_fonts() -> (String, String, String, String) {
    let font_regular = read_asset_base64("static/fonts/Oswald-Regular.ttf");
    let font_medium = font_regular.clone();
    let font_light = read_asset_base64("static/fonts/Oswald-Light.ttf");
    let favicon = read_asset_base64("static/favicon.ico");
    (font_regular, font_medium, font_light, favicon)
}

//通过嵌入CSS、字体和favicon构建完整的HTML文档
pub fn build_full_html(title: &str, body: &str) -> String {
    let style = read_style_css();
    let (font_regular, font_medium, font_light, favicon) = read_fonts();

    let css = format!(
        r#"
<link rel="icon" href="data:image/x-icon;base64,{}">
<style>
    @font-face {{
        font-family: 'Oswald';
        src: url(data:font/truetype;charset=utf-8;base64,{}) format('truetype');
        font-weight: 400;
        font-style: normal;
    }}
    @font-face {{
        font-family: 'Oswald';
        src: url(data:font/truetype;charset=utf-8;base64,{}) format('truetype');
        font-weight: 700;
        font-style: normal;
    }}
    @font-face {{
        font-family: 'Oswald';
        src: url(data:font/truetype;charset=utf-8;base64,{}) format('truetype');
        font-weight: 300;
        font-style: normal;
    }}
    {}
</style>
"#,
        favicon, font_regular, font_medium, font_light, style
    );

    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{}</title>
    {}
</head>
<body>
    {}
</body>
</html>"#,
        title, css, body
    )
}

pub fn open_in_browser(file_path: &str) {
    println!("Opening file in browser: {}", file_path);

    #[cfg(target_os = "windows")]
    {
        Command::new("cmd")
            .args(&["/C", "start", file_path])
            .spawn()
            .expect("Failed to open browser on Windows");
    }
}
